import { ExportOutlined, GlobalOutlined, LinkOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProForm,
  ProFormCascader,
  ProFormDateRangePicker,
  ProFormRadio,
  ProList,
  QueryFilter,
} from '@ant-design/pro-components';
import { Button, Cascader, Form, FormInstance, Image, Input, Space, Tag, Typography } from 'antd';
import RcResizeObserver from 'rc-resize-observer';
import React, { useEffect, useRef, useState } from 'react';

import { getApi } from '@/requestConfig';
import {
  getPretreatmentRecordAreaCascaders,
  getPretreatmentRecordSourceList,
  pagePretreatmentRecord,
} from '@/services/api/api-datahub-record';
import { useAccess } from '@umijs/max';
import moment from 'moment';
import CheckboxRadio from './ChannelCheckboxRadio';
import DetialRecord from './DetailRecord';
const { Paragraph, Text } = Typography;

interface PageContainerDatahubRecordProps {}

const PageContainerDatahubRecord: React.FC<PageContainerDatahubRecordProps> = (props) => {
  const access = useAccess();
  const [responsive, setResponsive] = useState(false);
  const [width, setWidth] = useState(500);
  const formRef = useRef<FormInstance>();
  const userRef = useRef<ActionType>();

  const [sources, setSourceState] = useState<DatahubRecordData.SourceList[]>([]);
  const [sourceSelectChannelIds, setSourceSelectChannelIdsState] = useState<string[]>([]);
  const [sourceOptions, setSourceOptions] = useState<DatahubRecordData.SourceList[]>([]);
  const [areaList, setAreaList] = useState<DatahubRecordData.ChannelList[]>([]);
  const [total, setTotal] = useState(0);
  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({
    dataReleaseTimes: [moment().subtract(89, 'days'), moment()],
  });

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await pagePretreatmentRecord({ ...params, ...queryParam });
    setTotal(response.data.total);
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  const getShowSourceList = (list: DatahubRecordData.SourceList[]) => {
    //级联数据
    let cascaderSourcesData = new Array();
    //分组处理
    const sourcesGroupByData = list.groupBy((item: { levelName: any }) => item.levelName);

    if (sourcesGroupByData.中央媒体 !== undefined) {
      cascaderSourcesData.push({
        value: 1000,
        label: '中央媒体',
        children: sourcesGroupByData.中央媒体
          .sort((n1: { seq: number }, n2: { seq: number }) => {
            return n1.seq - n2.seq;
          })
          .map((item: { id: string; name: string; channelId: string; channelName: string }) => {
            return {
              value: item.id,
              label: `${item.name} - ${item.channelName}`,
              channelId: item.channelId,
            };
          }),
      });
    }

    if (sourcesGroupByData.市属媒体 !== undefined) {
      cascaderSourcesData.push({
        value: 2000,
        label: '市属媒体',
        children: sourcesGroupByData.市属媒体
          .sort((n1: { seq: number }, n2: { seq: number }) => {
            return n1.seq - n2.seq;
          })
          .map((item: { id: string; name: string; channelId: string; channelName: string }) => {
            return {
              value: item.id,
              label: `${item.name} - ${item.channelName}`,
              channelId: item.channelId,
            };
          }),
      });
    }

    if (sourcesGroupByData.区县媒体 !== undefined) {
      cascaderSourcesData.push({
        value: 3000,
        label: '区县媒体',
        children: sourcesGroupByData.区县媒体
          .sort((n1: { seq: number }, n2: { seq: number }) => {
            return n1.seq - n2.seq;
          })
          .map((item: { id: string; name: string; channelId: string; channelName: string }) => {
            return {
              value: item.id,
              label: `${item.name} - ${item.channelName}`,
              channelId: item.channelId,
            };
          }),
      });
    }

    return cascaderSourcesData;
  };

  /**
   * 获取来源列表
   * @param value
   */
  const getSourceList = async (media: string) => {
    const response = await getPretreatmentRecordSourceList();

    if (response.code === 0) {
      setSourceOptions(getShowSourceList(response.data));
      setSourceState(response.data);
    }
  };

  const getAreaList = async () => {
    const res = await getPretreatmentRecordAreaCascaders();
    setAreaList(res.data);
  };

  useEffect(() => {
    getSourceList(' ');
    getAreaList();
  }, []);

  return (
    <PageContainer
      style={{ background: '#FFF' }}
      header={{
        // title: (
        //   <Alert
        //      message="该功能目前处于试运行阶段，由于数据量较少，仍在不断完善中。如有任何问题或建议，请联系负责人房一以获取更多帮助，联系电话：13320207320"
        //      type="info"
        //     />
        //    ),
        breadcrumb: {
          items: [],
        },
        style: {
          paddingBlockEnd: 0,
        },
      }}
      content={
        <RcResizeObserver
          key="resize-observer"
          onResize={(size) => {
            setWidth(size.width);
          }}
        >
          <QueryFilter
            submitter={false}
            span={24}
            labelWidth="auto"
            split
            formRef={formRef}
            initialValues={{
              channelIds: [], //渠道=全部
              levelId: 'all', //媒体=全部
              sourceIds: [], //媒体选择框=空
              area: '500000000000', //区域=重庆
              areaIds: [], //区域选择框=空
              time: '最近90天',
              dataReleaseTimes: [moment().subtract(89, 'days'), moment()],
            }}
            layout="horizontal"
            onFinish={async (value) => {
              if (value.levelId === 'all' || value.levelId === 'clear' || value.levelId === '') {
                value.levelIds = [];
              } else {
                value.levelIds = [value.levelId];
              }

              if (value.sourceIds != undefined && value.sourceIds.length !== 0) {
                let sourceIds = new Array();

                value.sourceIds.forEach((item: any[]) => {
                  if (item.length == 1) {
                    sourceIds = sourceIds.concat(
                      sources.filter((i) => i.levelId == item[0].toString()).map((i) => i.id),
                    );
                  } else {
                    const option = item[item.length - 1];
                    sourceIds.push(option);
                  }
                });
                value.sourceIds = sourceIds;
              }

              if (value.areaIds != undefined && value.areaIds.length !== 0) {
                let areaIds = new Array();

                value.areaIds.forEach((item: any[]) => {
                  const option = item[item.length - 1];
                  areaIds.push(option);
                });

                value.areaIds = areaIds;
              }

              console.log('====2==onFinish====', value);

              setQueryParamState({ ...queryParam, ...value });
              userRef.current?.reloadAndRest();
            }}
          >
            <ProForm.Group title="查询">
              <div
                style={{
                  display: 'flex',
                  width: (width / 3) * 2,
                }}
              >
                <Form.Item name="dataName" style={{ maxWidth: (width / 3) * 2, width: '100%' }}>
                  <Input.Search
                    placeholder="搜索"
                    enterButton="搜索"
                    allowClear
                    onSearch={(value) => {
                      formRef.current?.setFieldValue('dataName', value);
                      formRef.current?.submit();
                    }}
                  />
                </Form.Item>
              </div>
            </ProForm.Group>
            <ProForm.Group title="渠道">
              <Form.Item name={'channelIds'}>
                <CheckboxRadio
                  vlaues={sourceSelectChannelIds}
                  onChange={(vlaues) => {
                    let levelId = formRef.current?.getFieldValue('levelId');

                    console.log('====levelId,vlaues====', levelId, '===', vlaues);

                    if (levelId == '') {
                      levelId = 'all';
                      formRef.current?.setFieldValue('levelId', 'all');
                    }

                    let showSources = new Array();

                    if (vlaues.length === 0) {
                      if (levelId == 'all') {
                        showSources = sources;
                      } else {
                        //空的 是 全部
                        const filterSources = sources.filter((item) => {
                          return levelId === item.levelId;
                        });
                        showSources = showSources.concat(filterSources);
                      }
                    } else {
                      //过滤出要展示的 媒体来源
                      vlaues.forEach((channelId) => {
                        const filterSources = sources.filter((item) => {
                          if (levelId === 'all') {
                            return channelId === item.channelId;
                          } else {
                            return levelId === item.levelId && channelId === item.channelId;
                          }
                        });
                        showSources = showSources.concat(filterSources);
                      });
                    }

                    console.log('====showSources====', showSources);

                    setSourceOptions(getShowSourceList(showSources));
                    formRef.current?.setFieldValue('channelIds', vlaues);
                    formRef.current?.setFieldValue('sourceIds', []);
                    formRef.current?.submit();
                  }}
                />
              </Form.Item>
            </ProForm.Group>

            <ProForm.Group title="媒体">
              <ProFormRadio.Group
                name="levelId"
                radioType="button"
                options={[
                  { label: '全部', value: 'all' },
                  { label: '中央媒体', value: '1000' },
                  { label: '市属媒体', value: '2000' },
                  { label: '区县媒体', value: '3000' },
                ]}
                fieldProps={{
                  onChange: () => {
                    const levelId = formRef.current?.getFieldValue('levelId');
                    const channelIds = formRef.current?.getFieldValue('channelIds');

                    let showSources = new Array();

                    if (channelIds.length === 0) {
                      //空的 是 全部

                      if (levelId === 'all') {
                        showSources = showSources.concat(sources);
                      } else {
                        const filterSources = sources.filter((item) => {
                          return levelId === item.levelId;
                        });
                        showSources = showSources.concat(filterSources);
                      }
                    } else {
                      //过滤出要展示的 媒体来源
                      channelIds.forEach((channelId: string) => {
                        const filterSources = sources.filter((item) => {
                          if (levelId === 'all') {
                            return channelId === item.channelId;
                          } else {
                            return levelId === item.levelId && channelId === item.channelId;
                          }
                        });
                        showSources = showSources.concat(filterSources);
                      });
                    }

                    setSourceOptions(getShowSourceList(showSources));
                    formRef.current?.setFieldValue('sourceIds', []);
                    formRef.current?.submit();
                  },
                }}
              />
              <ProFormCascader
                name="sourceIds"
                placeholder="选择媒体"
                allowClear
                fieldProps={{
                  options: sourceOptions,
                  style: {
                    width: (width / 3) * 1.5,
                  },
                  multiple: true,
                  allowClear: true,
                  showSearch: true,
                  maxTagCount: 'responsive',
                  showCheckedStrategy: Cascader.SHOW_PARENT,
                  displayRender: (labels: string[], selectedOptions?: any[]) => {
                    return labels.map((label, i) => {
                      const option = selectedOptions[i];
                      if (i === labels.length - 1) {
                        return <span key={option.value}>{label}</span>;
                      }
                      return <span key={option.value}>{label} / </span>;
                    });
                  },
                  onClear() {
                    formRef.current?.setFieldValue('levelId', 'clear');
                    formRef.current?.submit();
                  },
                  onChange(value, selectOptions) {
                    const levelId = formRef.current?.getFieldValue('levelId');

                    if (levelId === 'clear') {
                      setSourceOptions(getShowSourceList(sources));
                      formRef.current?.setFieldValue('levelId', 'all');
                      setSourceSelectChannelIdsState([]);
                      formRef.current?.setFieldValue('channelIds', []);
                    } else {
                      if (selectOptions.length === 0) {
                        formRef.current?.setFieldValue('levelId', 'all');
                      } else {
                        //清除 媒体 button 选中
                        formRef.current?.setFieldValue('levelId', '');

                        let setChannelIds = new Set<string>();

                        console.log('======selectOptions======', selectOptions);

                        selectOptions.forEach((item) => {
                          if (item.length == 1) {
                            item[0].children.forEach((i: { channelId: string }) => {
                              setChannelIds.add(i.channelId);
                            });
                          } else {
                            const option = item[item.length - 1];
                            setChannelIds.add(option.channelId);
                          }
                        });

                        console.log('=================', [...setChannelIds]);

                        setSourceSelectChannelIdsState([...setChannelIds]);
                        formRef.current?.setFieldValue('channelIds', [...setChannelIds]);
                      }
                    }
                    formRef.current?.submit();
                  },
                }}
              />
            </ProForm.Group>

            <ProForm.Group title="区域">
              <ProFormRadio.Group
                name="area"
                radioType="button"
                options={[{ label: '重庆', value: '500000000000' }]}
                fieldProps={{
                  onChange: () => {
                    console.log('=====11111111111111=====================');

                    formRef.current?.setFieldValue('areaIds', []);
                    formRef.current?.submit();
                  },
                }}
              />
              <ProFormCascader
                name="areaIds"
                placeholder="选择区域"
                // initialValue={['1']}
                fieldProps={{
                  options: areaList,
                  style: {
                    width: (width / 3) * 2,
                  },
                  multiple: true,
                  allowClear: true,
                  showSearch: true,
                  maxTagCount: 'responsive',
                  showCheckedStrategy: Cascader.SHOW_PARENT,
                  onClear() {
                    formRef.current?.setFieldValue('area', 'clear');
                    formRef.current?.submit();
                  },
                  onChange: (e) => {
                    const area = formRef.current?.getFieldValue('area');

                    console.log('=========', area);

                    if (area === 'clear' || area === '') {
                      formRef.current?.setFieldValue('area', '500000000000');
                    } else {
                      formRef.current?.setFieldValue('area', '');
                    }
                    formRef.current?.submit();
                  },
                }}
              />
            </ProForm.Group>

            <ProForm.Group title="发布时间">
              <ProFormRadio.Group
                name="time"
                radioType="button"
                options={[
                  { label: '今天', value: '今天' },
                  { label: '本月', value: '本月' },
                  { label: '上月', value: '上月' },
                  { label: '最近7天', value: '最近7天' },
                  { label: '最近60天', value: '最近60天' },
                  { label: '最近90天', value: '最近90天' },
                ]}
                fieldProps={{
                  onChange: () => {
                    const time = formRef.current?.getFieldValue('time');
                    if (time === '今天') {
                      formRef.current?.setFieldValue('dataReleaseTimes', [moment(), moment()]);
                    } else if (time === '本月') {
                      formRef.current?.setFieldValue('dataReleaseTimes', [
                        moment().startOf('month'),
                        moment().endOf('month'),
                      ]);
                    } else if (time === '上月') {
                      formRef.current?.setFieldValue('dataReleaseTimes', [
                        moment().startOf('month').subtract(1, 'months'),
                        moment().endOf('month').subtract(1, 'months'),
                      ]);
                    } else if (time === '最近7天') {
                      formRef.current?.setFieldValue('dataReleaseTimes', [
                        moment().subtract(6, 'days'),
                        moment(),
                      ]);
                    } else if (time === '最近60天') {
                      formRef.current?.setFieldValue('dataReleaseTimes', [
                        moment().subtract(59, 'days'),
                        moment(),
                      ]);
                    } else if (time === '最近90天') {
                      formRef.current?.setFieldValue('dataReleaseTimes', [
                        moment().subtract(89, 'days'),
                        moment(),
                      ]);
                    }
                    formRef.current?.submit();
                  },
                }}
              />
              <ProFormDateRangePicker
                name="dataReleaseTimes"
                fieldProps={{
                  onChange(dates, dateStrings) {
                    formRef.current?.setFieldValue('time', ' ');
                    formRef.current?.submit();
                  },
                }}
              />
            </ProForm.Group>
          </QueryFilter>
        </RcResizeObserver>
      }
    >
      <ProList<DatahubRecordData.PretreatmentRecordPage>
        ghost
        actionRef={userRef}
        headerTitle={
          <h2>
            搜索得到：<span style={{ color: 'red' }}>{total}</span>条
          </h2>
        }
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            icon={<ExportOutlined />}
            onClick={() => {
              console.log(formRef.current?.getFieldsValue());
              const time = formRef.current?.getFieldValue('dataReleaseTimes');
              const param = 'startTime=' + time[0] + '&' + 'endTime=' + time[1];
              const exportExcelUrl = getApi() + '/datahub/pretreatment/record/export?' + param;
              window.open(exportExcelUrl);
            }}
          >
            数据导出
          </Button>,
          <Button type="primary" onClick={() => userRef.current?.reload()}>
            刷新
          </Button>,
        ]}
        // toolbar={{

        // }}
        request={request}
        itemLayout="vertical"
        rowKey="id"
        metas={{
          title: {
            render: (dom, entity) => (
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                {access.数据仓x配置x运营员 && (
                  <Tag color={entity.isExamine == 0 ? 'red' : 'green'}>
                    {entity.isExamine == 0 ? '未审核' : '已审核'}
                  </Tag>
                )}
                <Tag icon={<GlobalOutlined />} color="#55acee">
                  {entity.sourceName}
                </Tag>
                {/* <EditData
                    onRefurbish={userRef.current?.reload}
                    detailData={entity}
                    name={entity.dataName}
                  /> */}
                <DetialRecord
                  dataId={entity.id}
                  dataName={entity.dataName}
                  onRefurbish={userRef.current?.reload}
                />
              </div>
            ),
          },
          description: {
            render: (dom, entity) => (
              <>
                {entity.levelName && (
                  <Tag
                    color={
                      entity.levelId === '1000'
                        ? 'error'
                        : entity.levelId === '2000'
                        ? 'warning'
                        : 'success'
                    }
                  >
                    {entity.levelName}
                  </Tag>
                )}
                {entity.channelName && <Tag color="success">{entity.channelName}</Tag>}
                {entity.focusName && <Tag color="processing">{entity.focusName}</Tag>}
                {entity?.areas?.map((item) => (
                  <Tag>{item?.name}</Tag>
                ))}
              </>
            ),
          },
          actions: {
            render: (dom, entity) => [
              <div>
                <div style={{ textAlign: 'left' }}>
                  <a href={entity.dataSourceUrl} target="_blank" rel="noopener noreferrer">
                    <LinkOutlined />
                    查看原文
                  </a>
                  <span> 发布时间：{entity.dataReleaseTime}</span>
                </div>
                <div style={{ textAlign: 'left', marginTop: 5 }}>
                  标签：
                  {entity?.labels.slice(0, 10).map((item) => (
                    <Tag>{item?.name}</Tag>
                  ))}
                  {entity?.labels.length > 3 ? <Tag>...</Tag> : ''}
                </div>
                {('微信' == entity.channelName ||
                  '抖音' == entity.channelName ||
                  '今日头条' == entity.channelName ||
                  '微博' == entity.channelName) && (
                  <div style={{ textAlign: 'left', marginTop: 5 }}>
                    <Space size="large">
                      <span>点赞量：{entity.dataLikeCount}</span>
                      <span>评论量：{entity.dataCommentCount}</span>
                      <span>阅读量：{entity.dataReadCount}</span>
                      <span>转发量：{entity.dataForwardingCount}</span>
                      {'微信' == entity.channelName && <span>在看量：{entity.dataWatchCount}</span>}
                      {'抖音' == entity.channelName && <span>播放量：{entity.dataPlayCount}</span>}
                    </Space>
                  </div>
                )}
              </div>,
            ],
          },
          extra: {
            render: (dom: any, entity: DatahubRecordData.PretreatmentRecordPage) => {
              if ('广大' == entity.factoryName) {
                if ('电视视频' == entity.channelName) {
                  if (entity.dataEditionSnapshot && entity.dataEditionSnapshot.length > 0) {
                    return <Image width={470} height={235} src={entity.dataEditionSnapshot[0]} />;
                  } else {
                    return <></>;
                  }
                }
              } else {
                if ('电视视频' == entity.channelName) {
                  if (entity.dataEditionSnapshot && entity.dataEditionSnapshot.length > 0) {
                    return <Image width={172} height={235} src={entity.dataEditionSnapshot[0]} />;
                  } else {
                    return <></>;
                  }
                } else if ('电子报纸' == entity.channelName) {
                  if (entity.dataEditionSnapshot && entity.dataEditionSnapshot.length > 0) {
                    return <Image width={172} height={235} src={entity.dataEditionSnapshot[0]} />;
                  } else {
                    return <></>;
                  }
                } else if ('微信' == entity.channelName) {
                  if (entity.dataEditionSnapshot && entity.dataEditionSnapshot.length > 0) {
                    return (
                      <Image
                        width={200}
                        height={172}
                        referrerPolicy="no-referrer"
                        src={entity.dataEditionSnapshot[0]}
                      />
                    );
                  } else {
                    return <></>;
                  }
                } else if ('抖音' == entity.channelName) {
                  if (entity.dataEditionSnapshot && entity.dataEditionSnapshot.length > 0) {
                    return <Image width={172} height={235} src={entity.dataEditionSnapshot[0]} />;
                  } else {
                    return <></>;
                  }
                } else if ('微博' == entity.channelName) {
                  if (entity.dataEditionSnapshot && entity.dataEditionSnapshot.length > 0) {
                    return <Image width={200} height={172} src={entity.dataEditionSnapshot[0]} />;
                  } else {
                    return <></>;
                  }
                } else if ('今日头条' == entity.channelName) {
                  if (entity.dataEditionSnapshot && entity.dataEditionSnapshot.length > 0) {
                    return <Image width={172} height={172} src={entity.dataEditionSnapshot[0]} />;
                  } else {
                    return <></>;
                  }
                }
              }
            },
          },
          content: {
            render: (dom, entity) => {
              if ('广大' == entity.factoryName) {
                if ('电视视频' == entity.channelName) {
                  return (
                    <div>
                      <Paragraph ellipsis={{ rows: 4, expandable: true, symbol: '查看更多' }}>
                        {entity.dataAbstracts}
                      </Paragraph>
                    </div>
                  );
                }
              } else {
                if ('电视视频' == entity.channelName) {
                  return (
                    <div>
                      <Paragraph ellipsis={{ rows: 4, expandable: true, symbol: '查看更多' }}>
                        {entity.dataAbstracts}
                      </Paragraph>
                    </div>
                  );
                } else if ('电子报纸' == entity.channelName) {
                  return (
                    <div>
                      <Paragraph ellipsis={{ rows: 4, expandable: true, symbol: '查看更多' }}>
                        {entity.dataAbstracts}
                      </Paragraph>
                    </div>
                  );
                } else if ('微信' == entity.channelName) {
                  return (
                    <div>
                      <Paragraph ellipsis={{ rows: 4, expandable: true, symbol: '查看更多' }}>
                        {entity.dataAbstracts}
                      </Paragraph>
                    </div>
                  );
                } else if ('微博' == entity.channelName) {
                  return false;
                } else if ('今日头条' == entity.channelName) {
                  return false;
                } else {
                  return false;
                }
              }
            },
          },
        }}
      />
    </PageContainer>
  );
};

export default PageContainerDatahubRecord;
